class Solution {
public:

    void reverse(string& s, int left, int right)
    {
        while (left <= right)
        {
            swap(s[left], s[right]);
            left++;
            right--;
        }
    }

    string reverseStr(string s, int k) {
        int i = 0;
        int count = 0;
        int begin = 0;
        int end = k - 1;
        while (i < s.size())
        {
            count++;
            if (count == 2 * k)
            {
                count = 0;
                reverse(s, begin, end);
                begin += 2 * k;
                end = begin + k - 1;
            }
            i++;
        }
        if (count != 0)
        {
            if (count < 2 * k && count >= k)
            {
                reverse(s, s.size() - count, s.size() - count + k - 1);
            }
            else if (count < k)
            {
                reverse(s, s.size() - count, s.size() - 1);
            }
        }
        return s;
    }
};